import 'dart:convert';
import 'dart:typed_data';
import 'package:http/http.dart' as http;

// 文生图请求/响应类型
class GenerationRequest {
  final String prompt;
  final String model;
  GenerationRequest({required this.prompt, required this.model});

  Map<String, dynamic> toJson() => {
        'prompt': prompt,
        'model': model,
      };
}

class GenerationDataItem {
  final String revisedPrompt;
  final String url;
  GenerationDataItem({required this.revisedPrompt, required this.url});

  factory GenerationDataItem.fromJson(Map<String, dynamic> json) {
    return GenerationDataItem(
      revisedPrompt: json['revised_prompt']?.toString() ?? '',
      url: json['url']?.toString() ?? '',
    );
  }
}

class GenerationResponse {
  final int created;
  final List<GenerationDataItem> data;
  final String model;
  final Map<String, dynamic>? usage;
  GenerationResponse({required this.created, required this.data, required this.model, this.usage});

  factory GenerationResponse.fromJson(Map<String, dynamic> json) {
    final list = (json['data'] as List? ?? []).map((e) => GenerationDataItem.fromJson(e as Map<String, dynamic>)).toList();
    return GenerationResponse(
      created: json['created'] is int ? json['created'] as int : int.tryParse(json['created']?.toString() ?? '') ?? 0,
      data: list,
      model: json['model']?.toString() ?? '',
      usage: json['usage'] as Map<String, dynamic>?,
    );
  }
}

// 图生图请求类型
class EditRequest {
  final String prompt;
  final String model;
  final List<Uint8List> images;
  final String responseFormat; // 'url' 或 'b64_json'
  final String? aspectRatio;
  EditRequest({
    required this.prompt,
    required this.model,
    required this.images,
    this.responseFormat = 'url',
    this.aspectRatio,
  });
}

class AiImageService {
  static const String _genEndpoint = 'https://api.bltcy.ai/v1/images/generations';
  static const String _editEndpoint = 'https://api.bltcy.ai/v1/images/edits';

  // 直接在代码中硬编码密钥（注意：生产环境不推荐）
  static const String _hardcodedApiKey = 'sk-bcVyc7AMydgccmQDnmWPVr6pg59UIqeTC3Edsxevzp2DYxVe';

  static String _resolveApiKey(String? explicit) {
    final k = explicit ?? _hardcodedApiKey;
    if (k.isEmpty) {
      throw Exception('缺少 BLT API Key。请在 ai_image_service.dart 中设置 _hardcodedApiKey。');
    }
    return k;
  }

  static Future<GenerationResponse> generateImage(GenerationRequest body, {String? apiKey}) async {
    final key = _resolveApiKey(apiKey);
    final res = await http.post(
      Uri.parse(_genEndpoint),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $key',
      },
      body: jsonEncode(body.toJson()),
    );
    if (res.statusCode < 200 || res.statusCode >= 300) {
      throw Exception('BLT API错误 ${res.statusCode}: ${res.body}');
    }
    final json = jsonDecode(res.body) as Map<String, dynamic>;
    return GenerationResponse.fromJson(json);
  }

  static Future<GenerationResponse> editImages(EditRequest body, {String? apiKey}) async {
    final key = _resolveApiKey(apiKey);
    final request = http.MultipartRequest('POST', Uri.parse(_editEndpoint));
    request.headers['Authorization'] = 'Bearer $key';

    request.fields['model'] = body.model;
    request.fields['prompt'] = body.prompt;
    request.fields['response_format'] = body.responseFormat;
    if (body.aspectRatio != null) {
      request.fields['aspect_ratio'] = body.aspectRatio!;
    }

    for (int i = 0; i < body.images.length; i++) {
      final bytes = body.images[i];
      request.files.add(http.MultipartFile.fromBytes('image', bytes, filename: 'image_$i.png'));
    }

    final streamed = await request.send();
    final res = await http.Response.fromStream(streamed);
    if (res.statusCode < 200 || res.statusCode >= 300) {
      throw Exception('BLT API错误 ${res.statusCode}: ${res.body}');
    }
    final json = jsonDecode(res.body) as Map<String, dynamic>;
    return GenerationResponse.fromJson(json);
  }
}